package server

import (
	"6-17yk/common/model/mysql"
	"6-17yk/common/model/redis"
	"6-17yk/common/pkg"
	"6-17yk/common/proto/user"
	"context"
	"errors"
	"gorm.io/gorm"
	"math/rand"
	"time"
)

func SmsSend(req *user.SmsSendReq) (*user.SmsSendResp, error) {
	Code := rand.Intn(9000) + 1000

	val := redis.Rdb.Set(context.Background(), "sms"+req.SouRes+req.Phone, Code, time.Minute*30).Val()
	return &user.SmsSendResp{Success: val}, nil
}

func Login(req *user.LoginReq) (*user.LoginResp, error) {
	val := redis.Rdb.Get(context.Background(), "smslogin"+req.Phone).Val()
	if val != req.SouRes {
		return nil, errors.New("验证码错误")
	}
	getUser, err := mysql.GetUser(req.Phone)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	if getUser.Phone == "" {
		m := mysql.User{
			Model:    gorm.Model{},
			Name:     req.Name,
			Phone:    req.Phone,
			Password: req.Password,
		}
		err := mysql.CreateUser(&m)
		if err != nil {
			return nil, errors.New("注册失败")
		}
	}
	if getUser.Password != req.Password {
		return nil, errors.New("密码错误")
	}
	claims := pkg.CustomClaims{ID: getUser.ID}
	token, err := pkg.NewJWT("2210a").CreateToken(claims)
	if err != nil {
		return nil, errors.New("token生成失败")
	}
	return &user.LoginResp{Success: token}, nil
}
